from typing import List, Optional
from tortoise.exceptions import DoesNotExist
from app.models.user import User  # 假设模型文件在 app/models/user.py
from app.dao.user_dao import user_dao

class UserService:
    """
    用户表基础服务类，提供增删改查功能
    """

    @staticmethod
    async def create_user(**kwargs) -> User:
        """
        创建新用户
        """
        data = {
            "username": kwargs["username"],
            "password_hash": kwargs["password_hash"],
            "email": kwargs["email"],
            "note": kwargs.get("note", None)
        }
        user = await user_dao.create(data)
        return user

    @staticmethod
    async def get_user_by_id(user_id: int) -> Optional[User]:
        """
        根据主键 ID 查询用户
        """
        try:
            user = await User.get(id=user_id)
            return user
        except DoesNotExist:
            return None

    @staticmethod
    async def get_all_users() -> List[User]:
        """
        查询所有用户
        """
        users = await user_dao.get_list()
        return users

    @staticmethod
    async def update_user(user_id: int, **kwargs) -> Optional[User]:
        """
        根据主键 ID 更新用户
        """
        try:
            user = await User.get(id=user_id)
            await user.update_from_dict(kwargs)
            await user.save()
            return user
        except DoesNotExist:
            return None

    @staticmethod
    async def delete_user(user_id: int) -> bool:
        """
        根据主键 ID 删除用户
        返回是否删除成功
        """
        try:
            user = await User.get(id=user_id)
            await user.delete()
            return True
        except DoesNotExist:
            return False
